const query=require('../db/mysql')
const {success,error}=require('../model/model')
class listController{
    getList=async (ctx)=>{
        const {id,keyword,pageIndex,pageSize,sortType,sortBy}=ctx.query
        let sql=`select * from users where 1=1 `
        let sqlCount=`select count(id) as total from users where 1=1 `
        if(id){
            sql+=`and id=${id} `
            sqlCount+=`and id=${id} `
        }
        if(keyword){
            sql+=`and title like "%${keyword}%" `
            sqlCount+=`and title like "%${keyword}%" `
        }
        if(sortType&&sortBy){
            sql+=`order by ${sortBy} ${sortType}`
        }
        if(pageIndex&&pageSize){
            sql+=`limit ${(pageIndex-1)*pageSize},${pageSize}`
        }
        const data=await query(sql)
        const count=await query(sqlCount)
        ctx.body=success({
            data:data,
            total:count[0].total
        })
    }
    addList=async (ctx)=>{
        const {username,password,nickname}=ctx.request.body
        const sql=`insert into users(username,password,nickname) values ("${username}","${password}","${nickname}")`
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body=success({
                username,
                password,
                nickname
            })
        }else{
            ctx.body=error('添加失败')
        }
    }
    editList=async (ctx)=>{
        const {username,password,nickname}=ctx.request.body
        const sql=`update users set username="${username}",password="${password}",nickname="${nickname}" `
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body=success('编辑成功')
        }else{
            ctx.body=error('编辑失败')
        }
    }
    delList=async (ctx)=>{
        const {id}=ctx.params
        const sql=`delete from users where id=${id}`
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body=success('删除成功')
        }else{
            ctx.body=error('删除失败')
        }
    }
}

module.exports=new listController()